package com.itlong.cloud.controller.user;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateUserInfoDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateUserInfoGetPageDTO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateEngineerProjectVO;
import com.itlong.cloud.POJO.VO.operate.OperateUserInfoGetOneVO;
import com.itlong.cloud.POJO.VO.operate.OperateUserInfoGetUserPageVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营-系统-人员控制器
 * </desc>
 *
 * @createDate 2017/09/28
 */
@RestController
@RequestMapping("/system/user")
public class OperateUserInfoController extends BaseController{
    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    RedisService redisService;

    /**
     * <desc>
     *      用户分页列表
     * </desc>
     *
     * @param pageDTO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @RequestMapping(path = "getPage",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getUserPage(OperateUserInfoGetPageDTO pageDTO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoGetPageDTO.class,request);
            String token = pageDTO.getToken();
            OperateUserInfoPO userInfoPO=iOperateUserInfoServiceClient.retrieve(token);
            if(StringUtils.isNotBlank(pageDTO.getUserNum())){
                if(!pageDTO.getUserNum().matches("[0-9]{1,50}")){
                    pageDTO.setUserNum(" ");
                }else{
                    pageDTO.setUserNum(Integer.valueOf(pageDTO.getUserNum()).toString());
                }
                if(pageDTO.getUserNum().equals("0")){
                    pageDTO.setUserNum("");
                }
            }
            Page<OperateUserInfoGetUserPageVO> page=iOperateUserInfoServiceClient.getPage(pageDTO);
            page.getRows().forEach(vo->{
                vo.setUserNum(StringHandlerUtil.autlSupply(8,vo.getUserNum(),"0"));
            });
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("isEngineerManage",iOperateUserInfoServiceClient.isEngineerManage(userInfoPO.getUserId())+"");
            messageVO=new MessageVO(JSON.toJSONString(resultMap),BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户getPage】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      查看用户详情
     * </desc>
     *
     * @param operateUserInfoPO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @RequestMapping(path = "getUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object getUserInfo(OperateUserInfoPO operateUserInfoPO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateUserInfoPO= HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoPO.class,request);
            OperateUserInfoGetOneVO vo=iOperateUserInfoServiceClient.getOneVO(operateUserInfoPO);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),vo);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户getUserInfo】查看用户详情失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      添加用户
     * </desc>
     *
     * @param operateUserInfoPO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_OPERATE_LOG_SAVE)
    @RequestMapping(path = "save",method = RequestMethod.POST)
    @ResponseBody
    public Object saveUser(OperateUserInfoPO operateUserInfoPO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateUserInfoPO= HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoPO.class,request);
            try{
                JSON.parseArray(operateUserInfoPO.getRelationInfo());
            }catch (Exception e){
                return new MessageVO(OperateErrorCodeEnum.USER_PROJECT_FORMAT_ERROR.getErrorCode());
            }
            int result=iOperateUserInfoServiceClient.save(operateUserInfoPO);
            if (result == OperateErrorCodeEnum.USERNAME_EXIST.getErrorCode().getSubCode()){
                messageVO=new MessageVO(OperateErrorCodeEnum.USERNAME_EXIST.getErrorCode());
            }else{
                messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户save】添加用户失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      更新用户
     * </desc>
     *
     * @param operateUserInfoPO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_OPERATE_LOG_UPDATE)
    @RequestMapping(path = "update",method = RequestMethod.POST)
    @ResponseBody
    public Object updateUser(OperateUserInfoPO operateUserInfoPO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateUserInfoPO= HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoPO.class,request);
            try{
                JSON.parseArray(operateUserInfoPO.getRelationInfo());
            }catch (Exception e){
                return new MessageVO(OperateErrorCodeEnum.USER_PROJECT_FORMAT_ERROR.getErrorCode());
            }
            int result = iOperateUserInfoServiceClient.update(operateUserInfoPO);
            if (result == OperateErrorCodeEnum.USERNAME_EXIST.getErrorCode().getSubCode()){
                messageVO=new MessageVO(OperateErrorCodeEnum.USERNAME_EXIST.getErrorCode());
            }else{
                messageVO=new MessageVO(operateUserInfoPO.getUserId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
        }catch(Exception e){
            throw new DataAccessException("【运营_系统_用户update】更新用户失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      删除用户（批量）
     * </desc>
     *
     * @param userIds
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_OPERATE_LOG_DELETE)
    @RequestMapping(path = "delete",method = RequestMethod.POST)
    @ResponseBody
    public Object deleteUser(String userIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userIds=request.getAttribute("userIds")==null?null:request.getAttribute("userIds").toString();
            iOperateUserInfoServiceClient.delete(userIds);
            messageVO=new MessageVO(userIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户delete】删除用户失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      重置用户密码（批量）
     * </desc>
     *
     * @param userIds 用户id 多个,号分隔
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_OPERATE_LOG_RESETPASSWORD)
    @RequestMapping(path = "resetPassword",method = RequestMethod.POST)
    @ResponseBody
    public Object resetPassword(String userIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userIds=request.getAttribute("userIds")==null?null:request.getAttribute("userIds").toString();
            iOperateUserInfoServiceClient.resetPassword(userIds);
            messageVO=new MessageVO(userIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户resetPassword】重置用户密码失败", e);
        }
        return messageVO;
    }


    /**
    *<desc>
    * 添加用户的个性化的列
    *</desc>
    *
    * @Author  chengshican
    * @Date   2020-12-22 10:51
    * @Param  token 登录用户的token，checkedIdKey 用户设置模块的key ， checkedIdValues 所选的用户的个性化的id，多个用逗号隔开
    * @Return
    * @Exception
    *
    */
    @UnAuthAccessRequired
    @RequestMapping(path = "/add/personalized",method = RequestMethod.POST)
    @ResponseBody
    public Object addPersonalized(String token,String checkedIdKey,String checkedIdValues){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            checkedIdKey=request.getAttribute("checkedIdKey")==null?null:request.getAttribute("checkedIdKey").toString();
            checkedIdValues=request.getAttribute("checkedIdValues")==null?null:request.getAttribute("checkedIdValues").toString();
            OperateUserInfoPO userInfoPO=iOperateUserInfoServiceClient.retrieve(token);
            String checkedId = redisService.get(userInfoPO.getUserId()+"_"+checkedIdKey);
            if (checkedId==null||checkedId.length()==0){
                //设备管理的默认列
                if ("DeviceListCheckedIds".equals(checkedIdKey)){
                    checkedIdValues="1,2,5,7,10,11";
                    //设备升级的默认列
                }else if ("DeviceUpGradeCheckedIds".equals(checkedIdKey)){
                    checkedIdValues="0,1,7,8,13";
                }
                redisService.set(userInfoPO.getUserId()+"_"+checkedIdKey,checkedIdValues);
            }else {
                redisService.set(userInfoPO.getUserId()+"_"+checkedIdKey,checkedIdValues);
            }

            messageVO= new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch(Exception e){
            throw new DataAccessException("【运营_系统_用户addPersonalized】设置用户个性化列失败", e);
        }
        return messageVO;
    }

    /**
     *<desc>
     * 获取用户的个性化的列
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-12-22 10:51
     * @Param  token 登录用户的token，checkedIdKey 用户设置模块的key
     * @Return  checkedIdValues 所选的用户的个性化的id，多个用逗号隔开
     * @Exception
     *
     */
    @UnAuthAccessRequired
    @RequestMapping(path = "/getPersonalized",method = RequestMethod.POST)
    @ResponseBody
    public Object getPersonalized(String token,String checkedIdKey){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            checkedIdKey=request.getAttribute("checkedIdKey")==null?null:request.getAttribute("checkedIdKey").toString();
            OperateUserInfoPO userInfoPO=iOperateUserInfoServiceClient.retrieve(token);
            if(userInfoPO == null){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            String checkedIdValues = redisService.get(userInfoPO.getUserId()+"_"+checkedIdKey);
            Map<String, String> map = new HashMap<>();

            String checkedId = redisService.get(userInfoPO.getUserId()+"_"+checkedIdKey);
            if (checkedId==null||checkedId.length()==0){
                //设备管理的默认列
                if ("DeviceListCheckedIds".equals(checkedIdKey)){
                    checkedIdValues="1,2,5,7,10,11";
                    //设备升级的默认列
                }else if ("DeviceUpGradeCheckedIds".equals(checkedIdKey)){
                    checkedIdValues="0,1,7,8,13";
                }
            }
            map.put("checkedIdValues",checkedIdValues);
            messageVO= new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        }catch(Exception e){
            throw new DataAccessException("【运营_系统_用户getPersonalized】获取用户个性化列失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取工程项目列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/2/1
     */
    @PostMapping("getEngineerProjectList")
    public Object getEngineerProjectList(HttpServletRequest request){
        try {
            OperateUserInfoDTO operateUserInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoDTO.class, request);
            if (operateUserInfoDTO == null || StringUtils.isBlank(operateUserInfoDTO.getUserId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<OperateEngineerProjectVO> list = iOperateUserInfoServiceClient.getEngineerProjectList(operateUserInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), list);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户】获取工程项目列表失败", e);
        }
    }
}
